package org.java.item.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.java.common.enums.ShoppingEnum;

import org.java.common.exception.ShoppingException;
import org.java.common.util.JsonUtils;
import org.java.common.vo.ResultVo;
import org.java.item.dao.SkuMapper;
import org.java.item.entity.Sku;
import org.java.item.service.SkuService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-4 0004 下午 3:04
 */
@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public ResultVo<Sku> getList(int page, int limit) {
        //开始分页
        PageHelper.startPage(page,limit);
        PageInfo<Sku> info=new PageInfo<>(skuMapper.selectAll());
        if (info.getList().isEmpty()) {
            //如果数据为空，抛出异常
            throw new ShoppingException(ShoppingEnum.SKU_LIST_NOT_FOUND);
        }
        //不为空，创建vo对象进行返回
        ResultVo<Sku> vo=new ResultVo<>();
        vo.setData(info.getList());
        vo.setCount(info.getTotal());
        //当前页
        vo.setPageNum(page);
        //总页数
        vo.setMaxPage(info.getPages());
        return vo;
    }

    @Override
    public void del(Long skuId) {
        int rows = skuMapper.deleteByPrimaryKey(skuId);
        System.out.println(rows);
        if (rows==0){
            System.out.println("删除失败");
            //删除失败

            throw  new ShoppingException(ShoppingEnum.BRAND_ADD_ERROR);
        }
        //删除成功，向队列发送消息，告诉es数据更新
        rabbitTemplate.convertAndSend("","es_queue",skuId);
    }
    @Override
    public void update(Sku sku) {
        int rows = skuMapper.updateByPrimaryKeySelective(sku);
        if (rows<=0){
            throw new ShoppingException(ShoppingEnum.SKU_UPDATE_ERROR);
        }
        //得到修改后的数据
        Sku updateSku = findById(sku.getId());
        String json = JsonUtils.serialize(updateSku);
        rabbitTemplate.convertAndSend("","es_update_queue",json);
    }
    @Override
    public void saveSku(Sku sku) {
        System.out.println(sku.getId());
        sku.setCreateTime(new Date());
        sku.setLastUpdateTime(new Date());
        int rows = skuMapper.insertSelective(sku);
        System.out.println(sku.getId());
        if (rows<=0){
            throw new ShoppingException(ShoppingEnum.SKU_ADD_ERROR);
        }
        //发送消息es
        rabbitTemplate.convertAndSend("","es_add_queue",JsonUtils.serialize(sku));
    }

    @Override
    public ResultVo<Sku> getListAll() throws IOException {
        List<Sku> list = skuMapper.selectAll();
        //开始向es存储数据
        BulkRequest bulkRequest=new BulkRequest();
        for (int i = 0; i < list.size(); i++) {
            bulkRequest.add(
                    new IndexRequest("shopping")
                            .source(JSON.toJSONString(list.get(i)), XContentType.JSON)
            );
            System.out.println(list.get(i));
        }
        restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.out.println("添加到es成功");
        return null;
    }

    @Override
    public Sku findById(Long id) {
        Sku sku = skuMapper.selectByPrimaryKey(id);
        return sku;
    }

    @Override
    public void cutInventory(Long skuId,Integer num) {
        skuMapper.cutInventory(skuId,num);
    }

    @Override
    public void rollbackInventory(Long skuId, Long inventory) {
        skuMapper.rollbackInventory(skuId,inventory);
    }
}
